package com.demo2do.boyle.client.web.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.demo2do.boyle.client.Constant;
import com.demo2do.boyle.client.handler.CookieHandler;
import com.demo2do.boyle.client.handler.OpenIdAuthHandler;
import com.demo2do.boyle.client.handler.ValidateCodeHandler;
import com.demo2do.boyle.client.service.CustomerService;
import com.demo2do.boyle.common.entity.customer.Customer;
import com.demo2do.boyle.common.entity.customer.Source;
import com.demo2do.core.entity.Result;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.web.resolver.Secure;

/**
 * 
 * @author Wilson
 */
@Controller
public class AuthenticationController {

    private static final Logger logger = LoggerFactory.getLogger(AuthenticationController.class);

    @Autowired
    private ValidateCodeHandler validateCodeHandler;
   
    @Autowired
    private CustomerService customerService;

    @Autowired
    private CookieHandler cookieHandler;
    
    @Autowired
    private OpenIdAuthHandler openIdAuthHandler;

    /**
     * login by phone and password, return customer
     * 
     * @param phone
     * @param password
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(
            HttpServletRequest request,
            @RequestParam("phone") String phone,
            @RequestParam("password") String password) {

        Result result = new Result();

        try {

            Customer customer = customerService.loadByMobile(phone);

            if(customer != null) {
                if(StringUtils.equals(password, customer.getPassword())) {

                    result.success().data("customer", customer);

                    // bind customer with openid
                    String openId = cookieHandler.getCookie(Constant.COOKIE_OPEN_ID, request);
                    if(openId != null) {
                        customerService.update(customer.bindOpenId(openId));
                    }

                } else {
                    result.fail().message("密码错误");
                }

            } else {
                result.fail().message("手机号未注册");
            }
            
        } catch (Exception e) {
            logger.info("login()", e);
            result.fail().message("服务器异常");
        }
  	
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * logout
     * 
     * @param phone
     * @param password
     * @return
     */
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
	public void logout(@Secure(property = "id") Integer customerId) {

		Result result = new Result();
		try {
			
			if (customerId != null) {
				Customer customer = customerService.load(Customer.class, customerId);
				boolean bool = openIdAuthHandler.logout(customer);
				if (bool) {
					result.success().message("登出成功！");
				} else {
					result.fail().message("登出失败！");
				}
				
			}

		} catch (Exception e) {
			logger.info("logout()", e);
			result.fail().message("服务器异常");
		}

	}

    /**
     * validate phone and validateCode in forget-password module
     * 
     * @param phone
     * @param validateCode
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/forget-password", method = RequestMethod.POST)
    public String forgetPassword(
            @RequestParam("phone") String phone,
            @RequestParam("validateCode") String validateCode) {

        Result result = new Result();

        try {

            if(validateCodeHandler.validateCode(phone, Constant.MODULE_FORGET_PASSWORD, validateCode)) { // validate code pass

                Customer customer = customerService.loadByMobile(phone);

                if(customer != null) {
                    result.success().data("customerId", customer.getId());
                } else {
                    result.fail().message("手机号未注册");
                }

            } else {
                result.fail().message("验证码错误");
            }

        } catch (Exception e) {
            logger.info("forgetPassword()", e);
            result.fail().message("服务器异常");
        }

        return JsonUtils.toJsonString(result);
    }

    /**
     * reset password
     * 
     * @param password
     * @param rePassword
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/reset-password", method = RequestMethod.POST)
    public String resetPassword(
    		@Secure(property = "id")  Integer customerId,
    		@RequestParam( value = "type", required = false) String type,
    		@RequestParam(value = "oldPassword", required = false) String oldPassword,
            @RequestParam("password") String password,
            @RequestParam("rePassword") String rePassword,
            @RequestParam("phone") String phone) {
    	

        Result result = new Result();

        try {

             if(StringUtils.equals(password, rePassword)) {

            	 
            	Customer customer = null;
            	
            	if (customerId != null) {
            		customer = customerService.load(Customer.class, customerId);
				}else {
					customer = customerService.loadByMobile(phone);
				}
            	
            	if(type != null && type.equals("reset")) {
            		if(customer.getPassword().equals(oldPassword)) {
            			customerService.update(customer.password(password));
                        result.success();
            		}else {
            			result.fail().message("原密码不正确");
            		}
            	}else {
            		if( customer.getMobile().equals(phone)) {
                        customerService.update(customer.password(password));
                        result.success();
                    } else {
                        result.fail().message("找不到手机号");
                    }
            	}

            } else {
                result.fail().message("密码不一致");
            }
            
        } catch (Exception e) {
            logger.info("resetPassword()", e);
            result.fail().message("服务器异常");
        }

       
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * modify password
     * @param oriPassword
     * @param password
     * @param rePassword
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/modify-password", method = RequestMethod.POST)
    public String modifyPassword(
    		@Secure(property = "id")  Integer customerId,
    		@RequestParam("oriPassword") String oriPassword,
    		@RequestParam("password") String password,
    		@RequestParam("rePassword") String rePassword,
    		@RequestParam("phone") String phone) {
    	
    	Result result = new Result();
    	
    	try {
    		
    		Customer customer = customerService.load(Customer.class, customerId);
    		
    		if (StringUtils.equals(customer.getPassword(), oriPassword)) {
    			
    			if(StringUtils.equals(password, rePassword)) {
    				
    				if(customer != null && customer.getMobile().equals(phone)) {
    					
    					customerService.update(customer.password(password));
    					result.success().message("密码重置成功");
    					
    				} else {
    					result.fail().message("找不到手机号");
    				}
    				
    			} else {
    				result.fail().message("密码不一致");
    			}
    			
    		} else {
    			result.fail().message("原密码输入错误，请重新输入！");
    		}
    		
    	} catch (Exception e) {
    		logger.info("resetPassword()", e);
    		result.fail().message("服务器异常");
    	}
    	
    	
    	return JsonUtils.toJsonString(result);
    }

    /**
     * register a new customer with validate code
     * 
     * @param phone
     * @param validateCode
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String register(
            @RequestParam("phone") String phone,
            @RequestParam("password") String password,
            @RequestParam("validateCode") String validateCode) {

        Result result = new Result();

        try {

            if(validateCodeHandler.validateCode(phone, Constant.MODULE_REGISTER, validateCode)) { // validate code pass

                Customer customer = customerService.loadByMobile(phone);

                if(customer != null) {
                    result.fail().message("手机号已注册");
                } else {
                    customer = new Customer(phone, Source.WECHAT);
                    customerService.create(customer);
                    customerService.update(customer.password(password));
                    result.success().data("customer", customer);
                }

            } else {
                result.fail().message("验证码错误");
            }

        } catch (Exception e) {
            logger.info("register()", e);
            result.fail().message("服务器异常");
        }

        return JsonUtils.toJsonString(result);
    }

    @ResponseBody
    @RequestMapping("/authenticate-failure")
    public String authenticateFailure() {
        Result result = new Result("3").message("需要登录");
        return JsonUtils.toJsonString(result);
    }

}
